layui.use(['layer', 'layedit', 'tinymce'], function () {

    var layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        layedit = layui.layedit;

    var tinymce = layui.tinymce;


    var initEditor = function () {
        var url = $('.upload_url').val();

        $('[id^=editor]').each(function (i) {
            var _this = $(this);
            var sortableId = _this.attr('id');
            var index = sortableId.substr(6);

            var editor_btn = 'editor' + index; // 编辑器元素

            var editor_elm = _this;
            var field = editor_elm.attr('data-field');
            var folder = editor_elm.attr('data-folder');
            var place = editor_elm.attr('data-place');
            var editor = editor_elm.attr('data-editor');

            if (field == '' || field == undefined) {
                field = 'file';
            }
            if (folder == '' || folder == undefined) {
                folder = 'default';
            }
            if (place == '' || place == undefined) {
                place = 'local';
            }
            if (editor == '' || editor == undefined) {
                //editor = 'layui';
                editor = 'tinymce';
            }

            if (editor == 'layui') {
                // layui 富文本编辑器
                url += '?method=layui&folder=' + folder + '&place=' + place;
                layedit.set({
                    // 图片上传接口
                    uploadImage: {
                        url: url, // 接口url
                        type: 'post', // 默认post
                    }
                });
                // 建立编辑器 layedit.set 一定要放在 build 前面，否则配置全局接口将无效
                window.editorIndex = layedit.build(editor_btn);
                editor_elm.attr('data-index', window.editorIndex);
            } else if (editor == 'tinymce') {
                // tinymce 富文本编辑器
                url += '?method=tinymce&folder=' + folder + '&place=' + place;
                tinymce.render({
                    elem: '#' + editor_btn,
                    // 支持tinymce所有配置
                    plugins: 'code quickbars print preview searchreplace autolink fullscreen image link media codesample table charmap hr advlist lists wordcount imagetools indent2em axupimgs',
                    toolbar: 'code undo redo | forecolor backcolor bold italic underline strikethrough | indent2em alignleft aligncenter alignright alignjustify outdent indent lineheight | link bullist numlist image axupimgs table codesample | formatselect fontselect fontsizeselect | preview | fullscreen',
                    height: 400,
                    fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
                    font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
                    lineheight_formats: '1 1.1 1.2 1.3 1.4 1.5 1.75 2 2.2 2.5 3',
                    // images_upload_url: url, //配置上传接口
                    // form:{
                    //     name: field, // 配置上传文件的字段名称
                    //     data: {
                    //         'field': field
                    //     }, //其他需要一起上传的数据
                    // },
                    images_upload_handler: function (blobInfo, success, failure) {
                        var xhr, formData;
                        var file = blobInfo.blob(); // 转化为易于理解的file对象
                        xhr = new XMLHttpRequest();
                        xhr.withCredentials = false;
                        xhr.open('POST', url);
                        xhr.onload = function() {
                            var json;
                            if (xhr.status != 200) {
                                //failure('HTTP Error: ' + xhr.status);
                                layer.msg(xhr.msg);
                                return;
                            }
                            json = JSON.parse(xhr.responseText);
                            if (!json || typeof json.location != 'string') {
                                failure('Invalid JSON: ' + xhr.responseText);
                                return;
                            }

                            if (json.code != 1) {
                                failure(json.msg);
                                return;
                            }
                            success(json.location);
                        };

                        formData = new FormData();
                        //formData.append('file', blobInfo.blob(), blobInfo.filename());
                        formData.append('file', file, file.name);
                        xhr.send(formData);
                    }
                }, (opt, edit) => {
                    // 加载完成后回调 opt 是传入的所有参数
                    // edit是当前编辑器实例，等同于tinymce.get返回值
                });
            }
        });

    };

    if ($('[id^=editor]').length > 0) {
        initEditor();
    }
});